package com.qjcc.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.qjcc.R;
import com.qjcc.util.Base64Util;
import com.qjcc.util.RandomStringGenerator;
import com.qjcc.util.SharedPreferencesUtil;
import com.qjcc.util.StringUtils;
import com.qjcc.util.UpdateManager;
import com.sctf.pushlibrary.util.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class IndexActivity extends Activity {

    private Button backButton;
    private TextView mTitle;
    private WebView mWebView;
    private Handler mHandler;
    private WebSettings mWebSettings;
    private Context myContext;
    private ProgressCustomDialog progressCustomDialog;
    private String base64Str;
    private File cameraFile;
    private LocationManager lm;
    private boolean isClickHome = true;
    private String fileType;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    private String mCurrentPhotoPath;

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 5000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setAddrType("all");
        option.disableCache(true);//禁止启用缓存定位
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            String success = "1";
            String msg = "";
            Map<String, String> map = new HashMap<String, String>();

            if(location != null){
                if (location.getLocType() == BDLocation.TypeServerError) {
                    msg = "服务端网络定位失败";
                    success = "0";
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    msg = "网络不同导致定位失败，请检查网络是否通畅";
                    success = "0";
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    msg = "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机";
                    success = "0";
                }

                Log.i("Longitude:", String.valueOf(location.getLongitude()) + "," + String.valueOf(location.getLatitude()) + ",address:" + location.getAddrStr());

                if(location.getLongitude() == 4.9E-324 || location.getLatitude() == 4.9E-324){
                    msg = "定位失败，请刷新页面后重试";
//                    msg = "lo：" + location.getLongitude() + location.getLocationDescribe();
                    success = "0";

                }else{
                    if(StringUtils.isEmpty(location.getAddrStr())){
                        success = "2";
                    }
                }

                if(success.equals("1") || success.equals("2")){
                    //定位成功
                    String longitude = String.valueOf(location.getLongitude());
                    String latitude = String.valueOf(location.getLatitude());
                    String address = location.getAddrStr();
                    map.put("longitude", longitude);
                    map.put("latitude", latitude);
                    map.put("address", address);
                }

            }else{
                msg = "定位失败，请刷新页面后重试";
                success = "0";
            }


            map.put("success", success);
            map.put("msg", msg);

            Gson gson = new Gson();
            String jsonStr = gson.toJson(map);
            mWebView.loadUrl("javascript:SCTF.API.STATUS.OK('" + jsonStr + "')");
            mLocationClient.stop();

            //Receive Location
            /*StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());*/
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        myContext = this;

        mTitle = (TextView) findViewById(R.id.text_title);
        backButton = (Button) findViewById(R.id.button_backward);
        mWebView = (WebView) this.findViewById(R.id.webView);

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        initLocation();

        //启动百度云推送
        String api_key = Utils.getMetaValue(IndexActivity.this, "api_key");
        Log.e("MainActivity", api_key);
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, api_key);

        backButton.setOnClickListener(new Button.OnClickListener(){//创建监听
            public void onClick(View v) {
                mWebView.goBack();
            }
        });

        mHandler = new Handler();

        // 设置支持JavaScript等
        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setBuiltInZoomControls(true);
        mWebSettings.setLightTouchEnabled(true);
        mWebSettings.setSupportZoom(true);
        mWebView.setHapticFeedbackEnabled(false);
        // mWebView.setInitialScale(0); // 改变这个值可以设定初始大小

        //地理位置相关
        mWebSettings.setGeolocationEnabled(true);

        //***最重要的方法，一定要设置，这就是出不来的主要原因
        mWebSettings.setDomStorageEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient() {
            //配置权限（同样在WebChromeClient中实现）
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                //newProgress 1~100的整数
                if(newProgress == 100){//加载完毕
                    if (progressCustomDialog != null && progressCustomDialog.isShowing()) {
                        progressCustomDialog.dismiss();
                    }
                }else {
                    //打开progressDialog
                    if (progressCustomDialog == null) {
                        progressCustomDialog = ProgressCustomDialog.init(myContext, "加载中...", true, null);
                        progressCustomDialog.setCanceledOnTouchOutside(false);
                        progressCustomDialog.show();
                    }else{
                        if(!progressCustomDialog.isShowing()){
                            progressCustomDialog.show();
                        }
                    }
                }
            }
        });
        mWebView.addJavascriptInterface(new WebPlugin(), "WebPlugin");

        //获得userId和token
        Map<String, String> users = SharedPreferencesUtil.getLoginUserMap(IndexActivity.this);
        String userId = users.get("userId");
        String tokenCode = users.get("tokenCode");
        String param = "userId=" + userId + "&tokenCode=" + tokenCode;
        mWebView.loadUrl(this.getString(R.string.testShowUrl)+ "&" + param);

        mWebView.setWebViewClient(new
            WebViewClient() {
                //重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                public boolean shouldOverrideUrlLoading (WebView view, String url){
                    if(url.startsWith("tel:")){
                        Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(url));
                        startActivity(intent);
                    }else{
                        Map<String, String> users = SharedPreferencesUtil.getLoginUserMap(IndexActivity.this);
                        String param = "userId=" + users.get("userId") + "&tokenCode=" + users.get("tokenCode");
                        view.loadUrl(url + "&" + param);
                    }
                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (url.contains("goindexlist-v2")) {
                        backButton.setVisibility(View.INVISIBLE);
                    } else {
                        backButton.setVisibility(View.VISIBLE);
                    }
                }
            }
        );

        //检查更新
        if(isClickHome){
            UpdateManager.getUpdateManager().checkAppUpdate(this, false, true);
            isClickHome = false;
        }else{
            UpdateManager.getUpdateManager().checkAppUpdate(this, false, false);
        }
    }

    /**
     * 插件类，在html的js里面直接调用
     */
    private class WebPlugin {

        /**
         * 注销
         */
        @JavascriptInterface
        public void relogin() {
            //清空user数据
            SharedPreferencesUtil.removeLoginUserInfo(IndexActivity.this);
            //跳转到登录页面
            Intent intent = new Intent(IndexActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }

        /**
         * 获取登录用户
         * @return
         */
        @JavascriptInterface
        public String getLoginUser() {
            Map<String, String> users = SharedPreferencesUtil.getLoginUserMap(IndexActivity.this);
            Gson gson = new Gson();
            String jsonStr = gson.toJson(users);
            return jsonStr;
        }

        /**
         * 获取照片
         * @return
         */
        @JavascriptInterface
        public void getPhoto(String type){
            try {
                dispatchTakePictureIntent(type);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void getAlbum(String type){
            String status=Environment.getExternalStorageState();
            if(status.equals(Environment.MEDIA_MOUNTED)){
                String filename = RandomStringGenerator.getRandomNumStrByLength(16)+".jpg";
                File dir = new File(Environment.getExternalStorageDirectory()+"/app_temp");
                if(!dir.exists()) dir.mkdirs();

                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                cameraFile = new File(dir, filename);
                Uri u = Uri.fromFile(cameraFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                fileType = type;
                startActivityForResult(intent, 0);
            }else{
                Toast.makeText(IndexActivity.this, "没有储存卡",Toast.LENGTH_LONG).show();
            }
        }

        /**
         * 获取地址信息
         * @return
         */
        @JavascriptInterface
        public void getLocation() {
            mLocationClient.start();
        }

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //若为camera跳回
        if (requestCode == 0 && resultCode == RESULT_OK) {
            if (cameraFile.exists()) {
                Bitmap bitmap = null;
                try {
                    FileInputStream fis = new FileInputStream(cameraFile);
                    bitmap = BitmapFactory.decodeStream(fis);
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (bitmap!=null) {
                    Log.e(getClass().getName(), (bitmap.getWidth()+","+bitmap.getHeight()));
                    base64Str = Base64Util.Bitmap2StrByBase64(bitmap);
                    Log.e("base64Str", base64Str);
                    mWebView.loadUrl("javascript:f_doUpload('" + base64Str + "', '" + fileType + "')");
                }
            } else if (data != null) {
                Uri selectImageUri = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectImageUri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
                base64Str = Base64Util.Bitmap2StrByBase64(bitmap);
                mWebView.loadUrl("javascript:f_doUpload('" + base64Str + "', '" + fileType + "')");
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM), "Camera");
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent(String fileType) throws IOException {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                return;
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                cameraFile = createImageFile();
                this.fileType = fileType;
                Uri photoURI = FileProvider.getUriForFile(IndexActivity.this,
                        "com.qjcc.fileProvider",
                        cameraFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, 0);
            }
        }
    }
}
